<template>
  <div class="commenBox">
    <h1 class="title">发表评论</h1>
    <hr>
    <textarea rows="3" maxlength="120" placeholder="请输入要评论的内容(最多120个字)" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postcomment">发表评论</mt-button>
    <div class="commentList">
      <div class="comment-item" v-for="(item,i) in commentList" :key="item.id">
        <h2 class="title">第{{i+1}}楼 用户:{{item.username}} 发表时间 {{item.add_time | dateFormat}} </h2>
        <div class="content">{{item.content}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="loadmore">加载更多</mt-button>
  </div>
</template>

<script>
import {Toast} from 'mint-ui';
export default {
  data() {
    return {
      pageindex: 1,
      commentList: [],
      msg:''
    }
  },
  mounted() {
    this.getcomments();
  },
  methods: {
    getcomments() { //获取评论列表
      // 这个artid要由父组件通过属性传值过来,接收在子组件中用props属性接收
      var url = "api/getcomments/" + this.artid + "?pageindex="+this.pageindex;
      console.log(url+'-----------');
      this.$http.get(url).then(res => {
        if (res.body.status === 0) {
          this.commentList = this.commentList.concat(res.body.message);
          console.log('获取评论成功');
        }else{
          console.log('评论加载失败');
        }
      })
    },
    loadmore(){ //点击加载更多
      this.pageindex++;
      this.getcomments();
    },
    postcomment(){
      //artid从父组件那里渲染的
      var url = "api/postcomment/"+ this.artid;
      this.$http.post(url,{"content":this.msg},{emulateJSON:true}).then(res=>{
        if(res.body.status === 0){
           Toast('发送成功');
         this.commentList.unshift({
            username:'匿名用户',
            add_time: new Date(),
            content:this.msg
          });

          this.msg ="";
        }else{
         Toast('发送失败');
        }
      })
    }
  },
  props: ["artid"]
}
</script>

<style lang="scss" scoped>
.commenBox {
  .title {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    margin: 0;
  }
  .comment-item {
    .title {
      font-size: 14px;
      background-color: #ccc;
      line-height: 30px;
      margin: 5px 0;
      font-weight: 200;
    }
    .content {
      text-indent: 30px;
      font-size: 13px;
      line-height: 30px;
    }
  }
}
</style>


